<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="168px">
      <el-form-item label="单据号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单据号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="转出仓库" prop="sourceScId">
        <el-select v-model="queryParams.sourceScId" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in ck" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="转入仓库" prop="targetScId">
        <el-select v-model="queryParams.targetScId" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in ck" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作人" prop="createBy">
        <el-select v-model="queryParams.createBy" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" prop="createTime">
        <el-date-picker clearable
                        v-model="queryParams.createMinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
        至
        <el-date-picker clearable
                        v-model="queryParams.createMaxTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核人" prop="approveBy">
        <el-select v-model="queryParams.approveBy" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.name"
                     :value="item.name" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" prop="approveTime">
        <el-date-picker clearable
                        v-model="queryParams.approveMinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
        至
        <el-date-picker clearable
                        v-model="queryParams.approveMaxTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option label="待审核" value="0" ></el-option>
          <el-option label="审核通过" value="3" ></el-option>
          <el-option label="审核拒绝" value="6" ></el-option>7
          <el-option label="部分收货" value="9" ></el-option>
          <el-option label="已收货" value="12" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:basicdatas:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:basicdatas:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:basicdatas:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="basicdatasList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据号" align="center" prop="code" width="170" show-overflow-tooltip/>
      <el-table-column label="转出仓库名称" align="center" prop="sourceScName" width="100"/>
      <el-table-column label="转入仓库名称" align="center" prop="targetScName" width="100"/>
      <el-table-column label="调拨数量" align="center" prop="totalNum" />
      <el-table-column label="调拨成本金额" align="center" prop="totalAmount" width="100">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.totalAmount).toLocaleString() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="createBy" width="100"/>
      <el-table-column label="操作时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span>{{ scope.row.status==0 ? '待审核' : scope.row.status==3 ? '审核通过' : scope.row.status==6 ? '审核拒绝' : scope.row.status==9 ? '部分收货' : '已收货' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="approveBy" width="100"/>
      <el-table-column label="审核时间" align="center" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="description" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="selectOrder(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="transferNumUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
            v-if="scope.row.status >= 3 && scope.row.status !== 12"
          >收货</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
            v-if="scope.row.status === 0"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="statusUpdate(scope.row)"
            v-if="scope.row.status === 0"
          >审批</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
            v-if="scope.row.status === 0"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <div style="display: inline-block;width: 300px;"><p>转出仓库：{{ this.form.sourceScName }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>转入仓库：{{ this.form.targetScName }}</p></div>
        <br>
        <div style="display: inline-block;width: 700px;">
          <p>
            备注： <textarea cols="70" rows="3" style="border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid" v-model="this.form.description" disabled/>
          </p>
        </div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>状态：<span :style="{color: statusColor}">{{ this.form.status==0 ? '待审核' : this.form.status==3 ? '审核通过' : this.form.status==6 ? '审核拒绝' : this.form.status==9 ? '部分收货' : '已收货'}}</span></p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>操作人：{{ this.form.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>操作时间：{{ parseTime(this.form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;" v-if="this.form.approveBy"><p>审核人：{{ this.form.approveBy }}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.form.approveTime"><p>审核时间：{{ parseTime(this.form.approveTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</p></div>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px">
        <el-table v-loading="loading" :data="this.tblScTransferOrderDetailList" @selection-change="handleSelectionChange">
          <el-table-column label="商品编号" align="left" prop="baseDataProduct.code" width="100px"/>
          <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="100px"/>
          <el-table-column label="商品SKU编号" align="left" prop="baseDataProduct.skuCode" width="100px"/>
          <el-table-column label="商品外部编号" align="left" prop="baseDataProduct.externalCode" width="100px"/>
          <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px"/>
          <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px"/>
          <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px"/>
          <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px"/>
          <el-table-column label="库存数量" align="left" prop="baseDataProduct.tblProductStock.stockNum" width="100px" v-if="title == '审批'"/>
          <el-table-column label="调拨数量" align="left" prop="transferNum" width="100px"/>
          <el-table-column label="已收货数量" align="left" prop="receiveNum" width="100px" v-if="title != '审批'"/>
          <el-table-column label="本次收货数量" align="left" prop="thisReceiveNum" width="100px" v-if="title == '收货'" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.thisReceiveNum" @input="getTotalNum"/>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
        <h3 style="margin:0 0 15px 10px;font-weight: bolder;">合计</h3>
        <div style="display: inline-block;margin-left:50px" >
          调拨数量：<input type="text" v-model="this.form.totalNum" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled>
        </div>
        <div style="display: inline-block;margin-left:50px" v-if="title === '查看'">
          调拨成本金额：<input type="text" v-model="this.form.totalAmount" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled>
        </div>
        <div style="display: inline-block;margin-left:50px" v-if="title === '收货'">
          本次收货数量：<input type="text" v-model="this.thisReceiveNum" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled>
        </div>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="success" @click="submitForm()" v-if="this.title == '收货'">收货</el-button>
        <el-button type="success" @click="submitForm(3)" v-if="this.title == '审批'">审批通过</el-button>
        <el-button type="danger" @click="submitForm(6)" v-if="this.title == '审批'&&this.form.status!=6">审批拒绝</el-button>
        <el-button @click="cancel" v-if="this.title != '查看'">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 拒绝原因 -->
    <el-dialog :title="title" :visible.sync="refuseOpen" width="500px" append-to-body>
      <el-form ref="refuseForm" :model="refuseForm" :rules="refuseRules" label-width="80px">
        <el-form-item label="拒绝原因" prop="reason">
          <el-input type="textarea" v-model="refuseForm.reason" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="refuseSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBasicdatas, getBasicdatas, delBasicdatas, addBasicdatas, updateBasicdatas } from "@/api/system/basicdatas";
import {parseTime} from "../../../utils/ruoyi";
import {customer, center, user} from "@/api/system/order";
import {listStock} from "@/api/system/stock";
import { addLog } from "@/api/system/log";

export default {
  name: "Basicdatas",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTblScTransferOrderDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库调拨单表格数据
      basicdatasList: [],
      // 仓库调拨单明细表格数据
      tblScTransferOrderDetailList: [],
      // 仓库下拉框
      ck: [],
      // 用户(审核人、操作人、销售员)下拉框
      user: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //拒绝原因弹窗
      refuseOpen:false,
      //弹窗状态颜色
      statusColor:"rgb(100, 100, 100)",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        sourceScId: null,
        targetScId: null,
        totalNum: null,
        totalAmount: null,
        description: null,
        createBy: null,
        createTime: null,
        approveBy: null,
        approveTime: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "单据号不能为空", trigger: "blur" }
        ],
        sourceScId: [
          { required: true, message: "转出仓库ID不能为空", trigger: "blur" }
        ],
        targetScId: [
          { required: true, message: "转入仓库ID不能为空", trigger: "blur" }
        ],
        totalNum: [
          { required: true, message: "调拨数量不能为空", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "调拨成本金额不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "操作人不能为空", trigger: "blur" }
        ],
        createById: [
          { required: true, message: "创建人ID不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "操作时间不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "修改人不能为空", trigger: "blur" }
        ],
        updateById: [
          { required: true, message: "修改人ID不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      },
      //拒绝原因
      refuseForm: {
        reason: ''
      },
      refuseRules: {
        reason: [
          { required: true, message: "拒绝原因不能为空", trigger: "blur" }
        ]
      },
      //商品库存记录的id列表
      stockLogList: [],
      //本次收货数量
      thisReceiveNum: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    /** 查询仓库调拨单列表 */
    getList() {
      this.loading = true;
      user(this.user).then(response => {
        this.user = response.rows;
      });
      center({categoryType:1}).then(response => {
        this.ck = response.rows;
      });
      listBasicdatas(this.queryParams).then(response => {
        this.basicdatasList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        sourceScId: null,
        targetScId: null,
        totalNum: null,
        totalAmount: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        approveBy: null,
        approveTime: null,
        status: null,
        refuseReason: null
      };
      this.tblScTransferOrderDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 查看按钮
    selectOrder(row){
      const id = row.id || this.ids
      getBasicdatas(id).then(response => {
        console.log(response);
        this.form = response.data;
        this.tblScTransferOrderDetailList = response.data.tblScTransferOrderDetailList;
        //根据仓库id和订单中的商品id，循环获取订单商品详情的库存数量
        for (let i = 0; i < this.tblScTransferOrderDetailList.length; i++) {
          this.selectProductStockList(this.form.sourceScId, this.tblScTransferOrderDetailList[i])
        }
        this.open = true;
        this.title = "查看";
      });

      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else if (row.status==6){
        this.statusColor = "rgb(255, 0, 0)";
      }
    },
    //获取库存列表
    selectProductStockList(scId, tblScTransferOrderDetail) {
      listStock({scId,productId:tblScTransferOrderDetail.productId}).then(response => {
        tblScTransferOrderDetail.baseDataProduct.tblProductStock = response.rows[0];
      });
    },
    // 循环遍历，获取收货总数量
    getTotalNum() {
      let sum = 0;
      for (let i = 0; i < this.tblScTransferOrderDetailList.length; i++) {
        sum += parseInt(this.tblScTransferOrderDetailList[i].thisReceiveNum);
      }
      if (sum >= 0) {
        this.thisReceiveNum = sum;
      } else {
        this.thisReceiveNum = 0;
      }
    },
    //收货按钮
    transferNumUpdate(row){
      this.reset();
      const id = row.id || this.ids
      getBasicdatas(id).then(response => {
        this.form = response.data;
        this.tblScTransferOrderDetailList = response.data.tblScTransferOrderDetailList.map(item => {
          return {
            ...item,
            thisReceiveNum: parseInt(item.transferNum) - parseInt(item.receiveNum) // 初始化值
          };
        });
        //根据仓库id和订单中的商品id，循环获取订单商品详情的库存数量
        for (let i = 0; i < response.data.tblScTransferOrderDetailList.length; i++) {
          this.selectProductStockList(this.form.sourceScId, this.tblScTransferOrderDetailList[i])
        }
        this.open = true;
        this.title = "收货";
        this.getTotalNum();
      });

      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else if (row.status==6){
        this.statusColor = "rgb(255, 0, 0)";
      }
    },
    //审批按钮
    statusUpdate(row){
      this.reset();

      const id = row.id || this.ids
      getBasicdatas(id).then(response => {
        this.form = response.data;
        this.tblScTransferOrderDetailList = response.data.tblScTransferOrderDetailList;
        //根据仓库id和订单中的商品id，循环获取订单商品详情的库存数量
        for (let i = 0; i < this.tblScTransferOrderDetailList.length; i++) {
          if (this.tblScTransferOrderDetailList[i].thisReceiveNum === undefined){
            this.tblScTransferOrderDetailList[i].thisReceiveNum = 0;
          }
          this.selectProductStockList(this.form.sourceScId, this.tblScTransferOrderDetailList[i])
        }
        this.open = true;
        this.title = "审批";
      });

      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else if (row.status==6){
        this.statusColor = "rgb(255, 0, 0)";
      }
    },
    //拒绝原因
    refuseSubmit() {
      this.$refs["refuseForm"].validate(valid => {
        if (valid) {
          this.form.status=6;
          this.form.approveBy='1';
          this.form.refuseReason=this.refuseForm.reason
          this.form.approveTime=new Date();
          updateBasicdatas(this.form).then(response => {
            this.$modal.msgError("审批拒绝");
            this.refuseOpen = false;
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 审核通过、审核拒绝按钮 */
    submitForm(status) {
      if (status==6){
        this.open = false;
        this.refuseOpen=true
      }else {
        for (let i = 0; i < this.tblScTransferOrderDetailList.length; i++) {
          if (this.tblScTransferOrderDetailList[i].transferNum > this.tblScTransferOrderDetailList[i].baseDataProduct.tblProductStock.stockNum){
            this.$modal.msgError("第"+(i+1)+"行调拨数量不能超过商品库存数量");
            return;
          }
          if ((parseInt(this.tblScTransferOrderDetailList[i].receiveNum) + parseInt(this.tblScTransferOrderDetailList[i].thisReceiveNum)) > this.tblScTransferOrderDetailList[i].transferNum){
            this.$modal.msgError("第"+(i+1)+"行收货数量不能超过对应调拨数量");
            return;
          }
        }
        let sum = 0;
        for (let i = 0; i < this.tblScTransferOrderDetailList.length; i++) {
          sum += parseInt(this.tblScTransferOrderDetailList[i].receiveNum) + parseInt(this.tblScTransferOrderDetailList[i].thisReceiveNum);
          this.tblScTransferOrderDetailList[i].receiveNum = sum;
        }
        if (this.form.totalNum === sum && sum !== 0){
          this.form.status=12;
        }else if (this.form.totalNum > sum && sum !== 0){
          this.form.status=9;
        }else {
          this.form.status = status;
        }
        this.form.tblScTransferOrderDetailList = this.tblScTransferOrderDetailList
        this.form.approveBy='系统管理员';
        this.form.approveTime=new Date();
        console.log(this.tblScTransferOrderDetailList)
        updateBasicdatas(this.form).then(response => {
          if (this.form.status === 3) {
            this.$modal.msgSuccess("审批成功");
          }
          this.open = false;
          this.getList();
        });
        console.log(this.form.status)
        if(this.form.status>=9){
          //出库审核通过后添加商品库存记录
          for (let i = 0; i < this.form.tblScTransferOrderDetailList.length; i++) {
            let stockNum = (this.form.tblScTransferOrderDetailList[i].baseDataProduct.tblProductStock.stockNum - this.form.tblScTransferOrderDetailList[i].transferNum) - this.form.tblScTransferOrderDetailList[i].baseDataProduct.tblProductStock.stockNum;
            let curTaxAmount = this.form.tblScTransferOrderDetailList[i].taxPrice * (this.form.tblScTransferOrderDetailList[i].baseDataProduct.tblProductStock.stockNum - this.form.tblScTransferOrderDetailList[i].transferNum);
            let oriTaxAmount = this.form.tblScTransferOrderDetailList[i].baseDataProduct.tblProductStock.taxPrice * this.form.tblScTransferOrderDetailList[i].baseDataProduct.tblProductStock.stockNum;
            let taxAmount = curTaxAmount - oriTaxAmount;
            console.log(stockNum+","+taxAmount)
            let stockLog = {
              id: generateUniqueId(this.stockLogList),
              scId: this.form.sourceScId,
              productId: this.form.tblScTransferOrderDetailList[i].productId,
              oriTaxPrice: this.form.tblScTransferOrderDetailList[i].baseDataProduct.tblProductStock.taxPrice,
              curTaxPrice: this.form.tblScTransferOrderDetailList[i].taxPrice,
              oriStockNum: this.form.tblScTransferOrderDetailList[i].baseDataProduct.tblProductStock.stockNum,
              curStockNum: this.form.tblScTransferOrderDetailList[i].baseDataProduct.tblProductStock.stockNum - this.form.tblScTransferOrderDetailList[i].transferNum,
              stockNum: stockNum,
              taxAmount: taxAmount,
              createBy: '系统管理员',
              createById: '1',
              createTime: new Date(),
              bizId: this.form.id,
              bizCode: this.form.code,
              bizDetailId: this.form.tblScTransferOrderDetailList[i].id,
              bizType: 11,
            }
            addLog(stockLog).then(response => {
              this.$modal.msgSuccess("收货成功");
            })
          }
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除仓库调拨单编号为"' + ids + '"的数据项？').then(function() {
        return delBasicdatas(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 仓库调拨单明细序号 */
    rowTblScTransferOrderDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.$router.push({
        path: '/scTransferOrder/add',
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      this.$router.push({
        path:'/scTransferOrder/update',
        query:{
          id: id,
        }
      })
    },
    /** 仓库调拨单明细删除按钮操作 */
    handleDeleteTblScTransferOrderDetail() {
      if (this.checkedTblScTransferOrderDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的仓库调拨单明细数据");
      } else {
        const tblScTransferOrderDetailList = this.tblScTransferOrderDetailList;
        const checkedTblScTransferOrderDetail = this.checkedTblScTransferOrderDetail;
        this.tblScTransferOrderDetailList = tblScTransferOrderDetailList.filter(function(item) {
          return checkedTblScTransferOrderDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleTblScTransferOrderDetailSelectionChange(selection) {
      this.checkedTblScTransferOrderDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/basicdatas/export', {
        ...this.queryParams
      }, `basicdatas_${new Date().getTime()}.xlsx`)
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 重新获取数据
      vm.getList();
    });
  }
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}
</script>
